package com.wenjiang.consumer;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wenjiang.common.constat.RedisKey;
import com.wenjiang.common.dto.OrderParam;
import com.wenjiang.common.vo.GoodInfo;
import com.wenjiang.entity.MallGood;
import com.wenjiang.entity.MallOrder;
import com.wenjiang.service.MallOrderService;
import com.wenjiang.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 订单超时处理 队列
 * 死信消费者
 */

@Slf4j
@Component
public class OrderTimeOutConsumer {


    @Autowired
    MallOrderService mallOrderService;

    @Autowired
    RedisUtils redisUtils;

    // 并发数设置小一点 防止redis连接不够用导致并发异常
    @RabbitListener(queues = "orderTimeOutQueue",concurrency ="3" )
    public void  orderTimeOut(OrderParam orderParam){

        //获取所选的商品id和数量
        String goodIds[] = orderParam.getGoodId();


        int num[]=orderParam.getGoodCount();


        //查找订单是否被支付
        MallOrder mallOrder = mallOrderService.getById(orderParam.getOrderId());


        //修改订单状态
        if (mallOrder.getStatus()==0){
            log.info("订单号"+orderParam.getOrderId()+" 超时");
            UpdateWrapper<MallOrder> updateWrapper= new UpdateWrapper<>();
            updateWrapper.set("status",-1);
            updateWrapper.eq("order_id",orderParam.getOrderId());
            mallOrderService.update(updateWrapper);

            //恢复库存
            //扣除对应的库存
            for (int i=0;i<goodIds.length;i++){
//                //获取对象并添加库存
//                GoodInfo good = (GoodInfo)redisUtils.get(RedisKey.mallGoodKey + goodIds[i]);
//
//                good.setGoodCount(good.getGoodCount()+num[i]);
//                // 恢复库存
//                redisUtils.set(RedisKey.mallGoodKey + goodIds[i], good);
                // 添加库存
                redisUtils.incr(RedisKey.mallGoodCount+goodIds[i],num[i]);
                log.info("恢复库存成功");

            }


        }

    }

}
